#include "onps.h"
#include "net_tools/ping.h"
#include <nxos.h>

#define PING_TEST_EN      1 //* ipv4 ping测试使能
#define PING6_TEST_EN     0 //* ipv6 ping测试使能
#define PING4_DST_ADDR    "192.168.0.100" //* ipv4版本的ping目标地址
#define PING6_DST_ADDR    "2408:8214:418:9850:d4a1:4896:6b3b:3" //* ipv6版本的ping目标地址

extern BOOL EthInit(void);

#if PING_TEST_EN || PING6_TEST_EN
#if PING_TEST_EN
static void  ping_recv_handler(USHORT usIdentifier, void *pvFromAddr, USHORT usSeqNum, UCHAR *pubEchoData, UCHAR ubEchoDataLen, UCHAR ubTTL, UCHAR ubElapsedMSecs, void *pvParam)
{
  CHAR szSrcAddr[20]; 
  struct in_addr stInAddr; 
  stInAddr.s_addr = *(UINT *)pvFromAddr;   
#if SUPPORT_PRINTF
#if PRINTF_THREAD_MUTEX  
  os_thread_mutex_lock(o_hMtxPrintf);
#endif  
  printf("<Fr>%s, recv %d bytes, ID=%d, Sequence=%d, Data='%s', TTL=%d, time=%dms\r\n", 
          inet_ntoa_safe(stInAddr, szSrcAddr), (UINT)ubEchoDataLen, usIdentifier, usSeqNum, pubEchoData, (UINT)ubTTL, (UINT)ubElapsedMSecs); 
#if PRINTF_THREAD_MUTEX  
  os_thread_mutex_unlock(o_hMtxPrintf);              
#endif  
#endif
}
#endif
#endif

int main(int argc, char *argv[])
{
    EN_ONPSERR enErr;
    
    if(open_npstack_load(&enErr))
    {    
        printf("The open source network protocol stack (ver %s) is loaded successfully.\r\n", ONPS_VER);
        /* init ethcard */
        if(EthInit())
            goto __lblStart;     
    }
    else
    {
        printf("The open source network protocol stack failed to load, %s\r\n", onps_error(enErr));
    }
    return -1;
__lblStart:
    /* 使用ping命令 */
#if PING_TEST_EN || PING6_TEST_EN
#if PING_TEST_EN
    USHORT usSeqNum = 0; 
    UINT unErrCount = 0; 
    INT nPing = ping_start(AF_INET, &enErr); 
    if(nPing < 0)     
        printf("ping_start() failed, %s\r\n", onps_error(enErr));  
#endif  
#endif

    while (1) {
#if PING_TEST_EN || PING6_TEST_EN
#if PING_TEST_EN    
        if(nPing >= 0)
        {
            INT nRtnVal = ping(nPing, PING4_DST_ADDR, usSeqNum++, 64, NX_ClockGetMillisecond, ping_recv_handler, NULL, 3, NULL, &enErr); 
            if(nRtnVal <= 0)
            {
                unErrCount++;         
                os_thread_mutex_lock(o_hMtxPrintf);
                printf("no reply received, the current number of errors is %d, current error: %s\r\n", unErrCount, nRtnVal ? onps_error(enErr) : "recv timeout"); 
                os_thread_mutex_unlock(o_hMtxPrintf);
            }
        } 
#endif
#endif
    }

    return 0;
}
